<template>
  <div class="page-wrapper">
    <div class="login-container">
      <div class="logo">
        <img src="@/assets/Logo.png" alt="Logo" />
        <div class="identity-change">
          <router-link to="/admin-login" custom v-slot="{ navigate }">
            <button :class="{ active: $route.path === '/admin-login' }" @click="navigate">
              管理员登录
            </button>
          </router-link>
          <router-link to="/user-login" custom v-slot="{ navigate }">
            <button :class="{ active: $route.path === '/user-login' }" @click="navigate">
              用户登录
            </button>
          </router-link>
        </div>
      </div>

      <form @submit.prevent="handleSubmit">
        <div class="form-group">
          <input v-model="form.username" type="text" placeholder="手机号/邮箱" required />
        </div>

        <div class="form-group">
          <input v-model="form.password" type="password" placeholder="登录密码" required />
        </div>

        <div v-if="errorMessage" class="error-message">
          {{ errorMessage }}
        </div>

        <div class="remember-me">
          <label class="toggle-switch">
            <input v-model="form.remember" type="checkbox" id="remember" />
            <span class="slider"></span>
          </label>
          <label for="remember">记住密码</label>
        </div>

        <button type="submit" class="login-btn" :disabled="isLoading">
          {{ isLoading ? '登录中...' : '登录' }}
        </button>
        <a href="#" class="create-account">创建账号</a>
      </form>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { login, getCurrentUser } from '@/api'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

const form = reactive({
  username: '',
  password: '',
  remember: true
})

const isLoading = ref(false)
const errorMessage = ref('')

const handleSubmit = async () => {
  if (isLoading.value) return

  const phone = form.username.trim()
  const password = form.password.trim()
  if (!phone || !password) {
    errorMessage.value = '请输入管理员账号和密码'
    return
  }

  isLoading.value = true
  errorMessage.value = ''

  try {
    const response = await login({ phone, password })
    const payload = response?.data
    if (!payload?.token) {
      throw new Error(response?.message || '登录失败，请检查账号或密码')
    }

    userStore.setAuthState({ token: payload.token, userInfo: null })

    const userInfoRes = await getCurrentUser()
    const userInfo = userInfoRes?.data
    if (userInfo) {
      userStore.setUserInfo(userInfo)
    }

    if (!userInfo?.roles?.includes('ROLE_ADMIN')) {
      userStore.clearAuth()
      throw new Error('当前账号无管理员权限，请使用普通用户登录入口')
    }

    form.password = ''
    router.push('/manager')
  } catch (error) {
    console.error('管理员登录失败', error)
    userStore.clearAuth()
    if (error?.code === 4003) {
      errorMessage.value = error?.message || '账号已被封禁，无法登录，请联系管理员'
    } else {
      errorMessage.value = error?.message || '登录失败，请稍后重试'
    }
  } finally {
    isLoading.value = false
  }
}
</script>

<style scoped>
@import '@/CSS/LoginPageManager.css';
</style>
